Django Template Engine

Manish Patel

Aug 24, 2023

Step 1: Set Up the Django Project

  1. Install Django: Make sure you have Django installed. You can install it using the following command:
pip install django
  1. Create a Django Project: Open your terminal and navigate to the directory where you want to create your project. Then run the following command:
django-admin startproject TemplateDemo
  1. Navigate to Project Directory: Move into the project directory:
cd TemplateDemo

Step 2: Create a Django App

  1. Create an App: In the project directory, create a new app. Let’s call it “template_app”:
python manage.py startapp template_app
  1. Register template_app in settings.py

Step 3: Define the Views and Templates

  1. Define Views: Open template_app/views.py and define a simple view that passes some data to the template:
from django.shortcuts import render

def demo_view(request):
   context = {
       'name': 'John',
       'age': 25,
       'numbers': [1, 2, 3, 4, 5],
       'show_numbers': True,
   }
   return render(request, 'template_app/demo_template.html', context)

2. Create Templates Directory:

  • Inside the template_app directory, create a directory named templates.
  • This is where Django will look for your templates.

3. Create a Base Template: Inside the templates directory, create a file named base.html. Use Bootstrap for styling:

<!DOCTYPE html>
<html>
<head>
   <title>{% block title %}Django Template Demo{% endblock %}</title>
   <!-- Add Bootstrap CDN link here -->
   <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
   <div class="container">
       {% block content %}
       {% endblock %}
   </div>
</body>
</html>

4. Create a Template that Extends the Base Template:

  • Inside the templates directory, create a file named demo_template.html:
{% extends 'template_app/base.html' %}

{% block content %}
<h1>Hello, {{ name }}!</h1>
<p>You are {{ age }} years old.</p>

{% if show_numbers %}
   <ul>
       {% for number in numbers %}
           <li>{{ number }}</li>
       {% endfor %}
   </ul>
{% endif %}
{% endblock %}

Step 4: Configure URLs

APP URLS

  1. Define URLs: Open template_app/urls.py and define a URL pattern for your view:
from django.urls import path
from . import views

urlpatterns = [
    path('demo/', views.demo_view, name='demo'),
]

PROJECT URLS

  1. Include URLs in Project: In the main urls.py (located in the project folder), include the app’s URLs:
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
   path('admin/', admin.site.urls),
   path('template/', include('template_app.urls')),
]

Step 5: Run the Development Server

  1. Run Server: In the terminal, run the development server:
python manage.py runserver
  1. Access the Template: Open your web browser and navigate to http://127.0.0.1:8000/template/demo/.